﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Macaw.Moss2007.XmlSitemapSolution
{
    public class XmlSitemapIndexHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get 
            {
                return true;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            SPSite site = SPContext.Current.Site;
            SPWebApplication webapp = site.WebApplication;

            SPAlternateUrl alturl = webapp.AlternateUrls[HttpContext.Current.Request.Url];
            if (alturl == null)
            {
                context.Response.StatusCode = 500;
                context.Response.StatusDescription = string.Format("The Url \"{0}\" is not recognized as a valid AlternateUrl", HttpContext.Current.Request.Url.ToString());
                context.Response.End();
            }
            else
            {
                string SitemapStorageName = string.Format("XmlSitemap_{0}_{1}", site.ID, alturl.IncomingUrl);
                XmlSitemapStorageCollection storagecollection = new XmlSitemapStorageCollection(webapp);

                XmlSitemapStorage sitemapstorage = storagecollection.GetValue<XmlSitemapStorage>(SitemapStorageName);
                if (sitemapstorage != null)
                {
                    context.Response.Write(sitemapstorage.SitemapIndex);
                }
                else
                {
                    context.Response.StatusCode = 404;
                    context.Response.End();
                }
            }
        }

        #endregion
    }
}
